import plugin from '../../lib/plugins/plugin.js'
import {
  segment
} from "oicq";
import fetch from 'node-fetch'

/* 
作者: 花海里的秋刀鱼(717157592)
首发群: 258623209
时间: 2022.11.14 
*/

export class example extends plugin {
  constructor() {
    super({
      /** 功能名称 */
      name: '点餐',
      /** 功能描述 */
      dsc: '点餐',
      /** https://oicqjs.github.io/oicq/#events */
      event: 'message',
      /** 优先级，数字越小等级越高 */
      priority: 5000,
      rule: [{
        /** 命令正则匹配 */
        reg: '^点餐.*$',
        /** 执行方法 */
        fnc: 'order'
      }]
    })
  }


  async order(e) {
    try {
      let name = e.msg.replace(/#|点餐/g, "").trim()
      let url = `https://www.xiangha.com/so/?q=caipu&s=${name}`
      let response = await fetch(url) //调用接口获取数据
      let res = await response.text() //结果json字符串转
      let reg = /img alt(.*?)MTYweDEyMA/g
      let regs = /[\u4e00-\u9fa5]/g
      let list = res.match(reg)
      let footname = []
      let index
      let number
      let msg = []

      if (!list) return e.reply('未搜到该菜品', true)

      let menu = randomSortArray(list)

      if (menu.length > 5) {
        number = 5
      } else {
        number = menu.length
      }

      for (let i = 0; i < number; i++) {
        menu[i] = menu[i].replace(/的做法|\[图\]/g, '')
        footname[i] = menu[i].match(regs)
        footname[i] = footname[i].join('')
        index = menu[i].lastIndexOf("http")
        menu[i] = menu[i].slice(index)
        msg.push(footname[i], segment.image(menu[i]))
      }

      e.reply(msg)
      return true
    } catch (err) {
      e.reply('随机点餐报错了，请重试')
      return false
    }
  }
}

function randomSortArray(arr) {
  let stack = []
  while (arr.length) {
    let index = parseInt(Math.random() * arr.length)
    stack.push(arr[index])
    arr.splice(index, 1)
  }

  return stack
}